<!--
	作者：offline
	时间：2019-06-04
	描述：推送配置
-->
<template>
	<div class="m-view-pushSetting m-window">
		<div class="m-condition">
			<el-row :gutter="10">
				<el-form label-width="80px" :inline-message="true" label-position="left">
					<el-col :span="8">
						<el-form-item label="编码/名称">
							<el-input v-model="searchValue" placeholder="请输入业务类型编码/名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="2" :offset="6">
						<el-checkbox v-model="showState" @change="switchState">显示停用</el-checkbox>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="search(1)">查询</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="add">新增</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="edit" :disabled="showState">编辑</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="changePushState">{{btnText}}</el-button>
					</el-col>
				</el-form>
			</el-row>
		</div>
		<div class="m-agTable m-bottom">
			<ag-grid-vue
				class="m-agTableContent ag-theme-balham"
				:gridOptions="gridOptions"
				:columnDefs="columnDefs"
				:rowData="rowData"
				v-loading="loading"
			></ag-grid-vue>
		</div>
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				@prev-click="handlePrevClick"
				@next-click="handleNextClick"
				:current-page="pageInfo.current"
				:page-sizes="[30,50,100,150,200]"
				:page-size="pageInfo.size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pageInfo.total"
			></el-pagination>
		</div>

		<!--新增/编辑弹框 -->
		<el-dialog
			:title="title"
			v-if="dialogVisible"
			:visible.sync="dialogVisible"
			width="50%"
			:before-close="handleClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<el-form
				:model="ruleForm"
				ref="ruleForm"
				label-width="120px"
				class="demo-ruleForm"
				:rules="rules"
			>
				<el-form-item label="业务类型" prop="busTypeCode">
					<el-cascader
						v-model="ruleForm.busTypeCode"
						:options="busTypeOption"
						:props="props"
						:show-all-levels="false"
						clearable
					></el-cascader>
				</el-form-item>
				<el-form-item label="推送方向" prop="direction">
					<el-select v-model="ruleForm.direction" placeholder="请选择业务类型">
						<el-option
							v-for="item in dirOption"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="handleClose" :disabled.sync="disState">取消</el-button>
				<el-button type="primary" @click="saveData" :disabled.sync="disState">保存</el-button>
				<el-button type="primary" @click="saveData(1)" :disabled.sync="disState">保存与继续</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import _Api from "@/api";
// import excel from "@/views/excel";
import localeText from "@/i18n/agGridText";

export default {
	data () {
		return {
			// 弹窗标题
			title: '新增推送配置',
			// 弹窗是否显示
			dialogVisible: false,
			// 查询条件 
			searchValue: '',
			//  表格数据
			rowData: [],
			btnText: '停用',
			//  分页信息
			pageInfo: {
				size: 30,
				current: 1,
				total: 0
			},
			// 弹窗表单信息
			ruleForm: {
				busTypeCode: '',
				busTypeName: '',
				direction: ''
			},
			// 推送方向下拉内容
			dirOption: [
				{ label: '外部推送', value: 0 },
				{ label: '内部推送', value: 1 },
				{ label: '内外推送', value: 2 }
			],
			// 业务类型下拉内容
			busTypeOption: [],
			// 表单验证规则
			rules: {
				busTypeCode: [
					{ required: true, message: '请选择业务类型', trigger: 'blur' }
				],
				busTypeName: [
					{ required: true, message: '请输入业务类型名称', trigger: 'blur' }
				]
			},
			// 推送配置修改状态   
			mode: '',
			props: {
				checkStrictly: true,
				value: 'busTypeCode',
				label: 'busTypeName',
				children: 'childrenList'
			},
			inputDis: false,
			btnDisabled: false,
			delShow: false,
			showState: false,
			disState: false,
			loading: false
		}
	},
	beforeMount () {
		this.gridOptions = {
			context: {
				componentParent: this
			},
			rowSelection: "multiple",
			enableColResize: true,
			localeText: localeText,
			suppressRowClickSelection: true,
			//   getContextMenuItems: this.getContextMenuItems,
			onGridReady: function (params) {
				// params.api.sizeColumnsToFit()
			}
		}
		this.columnDefs = [
			{ headerName: "业务类型编码", field: "busTypeCode", checkboxSelection: true, headerCheckboxSelection: true, headerCheckboxSelectionFilteredOnly: true },
			{ headerName: "业务类型名称", field: "busTypeName" },
			{
				headerName: "推送方向",
				field: "direction",
				cellRenderer: function (params) {
					if (params.value == "0")
						return '<span class="ag-icon">外部推送</span>'
					else if (params.value == "1")
						return '<span class="ag-icon">内部推送</span>'
					else if (params.value == "2")
						return '<span class="ag-icon">内外推送</span>'
				}
			},
			{
				headerName: "状态",
				field: "state",
				cellRenderer: function (params) {
					if (params.value == "1")
						return '<span class="ag-icon">停用</span>'
					else if (params.value == "0")
						return '<span class="ag-icon">启用</span>'
				}
			}
		]
	},
	mounted () {
		this.search(1)
	},
	methods: {
		getContextMenuItems () {
			return []
		},
		// 编辑推送配置
		edit () {
			let row = this.gridOptions.api.getSelectedRows();
			if (row.length <= 0) {
				this.$alert("提示：请选择需要编辑的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			}
			if (row.length > 1) {
				this.$alert("提示：只能选择单条数据进行编辑操作！", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			}
			this.getBusTypeOptions()
			this.title = "编辑推送配置"
			this.btnShow = false
			this.ruleForm = row[0]
			this.mode = "edit"
			this.dialogVisible = true
		},
		// 获取推送配置列表数据
		search (flag) {
			if (flag) {
				this.pageInfo.current = 1
			}
			let params = {
				busTypeCode: this.searchValue,
				busTypeName: this.searchValue,
				state: this.showState ? 1 : 0,
				pageSize: this.pageInfo.size,
				currentPage: this.pageInfo.current
			}
			this.loading = true
			_Api.getPushList(params).then((response) => {
				let data = response.data
				if (data.code == "1") {
					if (data.total > 0) {
						this.gridOptions.api.setRowData(data.rows.splice(0))
						this.gridOptions.api.sizeColumnsToFit()
						this.pageInfo.total = data.total
					}
					else {
						this.gridOptions.api.setRowData([])
						this.pageInfo.total = 0
					}
				} else {
					this.$alert(data.info, {
						showClose: false,
						confirmButton: "确定",
						customClass: "alertFailure"
					})
				}
				this.loading = false
			}).catch((err) => {
				this.$alert(err.data.message, {
					showClose: false,
					confirmButton: "确定",
					customClass: "alertFailure"
				})
				this.loading = false
			})
		},
		// 每页显示条数改变回调
		handleSizeChange (val) {
			this.pageInfo.size = val
			this.search(1)
		},
		// 页码改变回调
		handleCurrentChange (val) {
			this.pageInfo.current = val
			this.search()
		},
		// 点击上一页回调
		handlePrevClick (val) {
			this.pageInfo.current = val
		},
		// 点击下一页回调
		handleNextClick (val) {
			this.pageInfo.current = val
		},
		// 筛选启用状态数据回调
		switchState (val) {
			if (val) {
				this.btnText = "启用"
			} else {
				this.btnText = "停用"
			}
			this.search(1)
		},
		// 停用/启用
		changePushState () {
			let row = this.gridOptions.api.getSelectedRows()
			let msg = this.showState ? '启用' : '停用'
			if (row.length <= 0) {
				this.$alert(`提示：请选择需要${msg}的数据`, {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			}
			// 提取所选业务类型id   
			let busIds = row.map(el => {
				return el.id
			})
			// 提取所选业务类型编码集合
			let codes = row.map(el => {
				return el.busTypeCode
			})
			let params = {
				state: this.showState ? 0 : 1,
				codes: codes.join(','),
				ids: busIds.join(',')
			}
			this.$confirm(`是否确认${msg}已选择数据？`, "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				_Api.changePushState(params).then(({ data }) => {
					if (data.code == 1) {
						this.$message({
							message: `所选数据已${msg}`,
							type: "success"
						})
						this.search(1)
					} else {
						this.$alert(data.info, {
							showClose: false,
							confirmButton: "确定",
							customClass: "alertFailure"
						})
					}
				}).catch((err) => {
					this.$alert(err.data.message, {
						showClose: false,
						confirmButton: "确定",
						customClass: "alertFailure"
					})
				})
			}).catch(() => {
				this.$message({
					message: `已取消${msg}`,
					type: "success"
				})
			})
		},
		// 点击新增回调
		add () {
			this.ruleForm = {
				busTypeCode: '',
				busTypeName: '',
				direction: 0
			}
			this.getBusTypeOptions()
			this.title = "新增推送配置"
			this.btnShow = true
			this.mode = "add"
			this.dialogVisible = true
		},
		// 关闭弹窗
		handleClose () {
			this.$refs.ruleForm.resetFields()
			this.$refs.ruleForm.clearValidate()
			this.dialogVisible = false
		},
		// 保存数据
		saveData (flag = 0) {
			const { busTypeCode } = this.ruleForm
			let params = {
				...this.ruleForm,
				busTypeCode: ""
			}
			if (Array.isArray(busTypeCode)) {
				params.busTypeCode = busTypeCode[busTypeCode.length - 1]
			} else {
				params.busTypeCode = busTypeCode
			}
			if (this.mode == "add") {
				this.$refs["ruleForm"].validate((valid) => {
					if (!valid) {
						return false
					}
					this.disState = true
					params.creator = this.$global.user.loginName
					params.creatorId = this.$global.user.id
					_Api.addPushSetting(params).then((response) => {
						let data = response.data
						if (data.code == "1") {
							this.$message({
								message: "保存成功",
								type: "success"
							})
							if (flag == 1) {
								this.$refs['ruleForm'].resetFields()
							} else {
								this.dialogVisible = false
							}
							this.search(1)
						} else {
							this.$alert(data.info, {
								showClose: false,
								confirmButton: "确定",
								customClass: "alertFailure"
							});
						}
						this.disState = false
					}).catch((err) => {
						this.$alert(err.data.message, {
							showClose: false,
							confirmButton: "确定",
							customClass: "alertFailure"
						})
						this.disState = false
					})
				})
			} else if (this.mode == "edit") {
				this.$refs["ruleForm"].validate((valid) => {
					if (valid) {
						this.disState = true
						params.modifyer = this.$global.user.loginName
						params.modifyerId = this.$global.user.id
						_Api.updatePushSetting(params).then((response) => {
							let data = response.data
							if (data.code == "1") {
								this.$message({
									message: "保存成功",
									type: "success"
								})
								this.dialogVisible = false
								this.search(1)
							} else {
								this.$alert(data.info, {
									showClose: false,
									confirmButton: "确定",
									customClass: "alertFailure"
								})
							}
							this.disState = false
						}).catch((err) => {
							this.$alert(err.data.message, {
								showClose: false,
								confirmButton: "确定",
								customClass: "alertFailure"
							})
							this.disState = false
						})
					} else {
						return false
					}
				})
			}
		},
		// 获取业务类型下拉内容
		getBusTypeOptions () {
			_Api.getParentsNodes().then(res => {
				let data = res.data
				if (data.code == '1') {
					this.busTypeOption = data.rows
					setCodeDisabled(this.busTypeOption)
				} else {
					this.$alert(data.info, {
						showClose: false,
						confirmButton: "确定",
						customClass: "alertFailure"
					})
				}
			})
				.catch(err => {
					this.$alert(err.data.message, {
						showClose: false,
						confirmButton: "确定",
						customClass: "alertFailure"
					})
				})
			// 递归设置节点是否可选择
			function setCodeDisabled (arr) {
				arr.forEach(item => {
					if (item.isLeaf == 0) {
						item.disabled = true
					} else {
						item.disabled = false
					}
					if (Array.isArray(item.childrenList)) {
						if (item.childrenList.length > 0) {
							setCodeDisabled(item.childrenList)
						} else {
							item.childrenList = null
						}
					}
				})
			}
		}
	}
}
</script>